package com.tulele.vtool.wechat.handler;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.tulele.vtool.mapper.KeywordDetailLogMapper;
import com.tulele.vtool.mapper.MessageDictInfoMapper;
import com.tulele.vtool.model.*;
import com.tulele.vtool.model.combinedEntity.UserBrandCombinedInfo;
import com.tulele.vtool.model.combinedEntity.WxPushUserInfo;
import com.tulele.vtool.model.logEntity.KeyWrodInfo;
import com.tulele.vtool.service.*;
import com.tulele.vtool.task.async.SendkefuMsgAsyncTask;
import com.tulele.vtool.utils.*;
import com.tulele.vtool.wechat.builder.ImageBuilder;
import com.tulele.vtool.wechat.builder.TextBuilder;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.util.*;

//菜单事件
@Component
@Slf4j
public class MenuHandler extends AbstractHandler {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private IArticleInfoService articleInfoService;

    @Autowired
    @Lazy
    protected MsgHandler msgHandler;

    @Autowired
    private SysGzhService sysGzhService;

    /**
     * 服务对象
     */
    @Resource
    private BDecorationArticlesService bDecorationArticlesService;

    /**
     * 商学院服务对象
     */
    @Resource
    private BBusinessInfoService bBusinessInfoService;

    /**
     * 服务对象
     */
    @Autowired
    private BMessageKefuService bMessageKefuService;

    @Autowired
    private IMessageDictInfoService messageDictInfoService;

    @Autowired
    private IUserBrandInfoService userBrandInfoService;

    @Autowired
    private UserGroupGzhService userGroupGzhService;

    @Autowired
    private KeywordDetailLogMapper keywordDetailLogMapper;

    @Autowired
    private SendkefuMsgAsyncTask sendkefuMsgAsyncTask;

    @SneakyThrows
    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) throws WxErrorException {
        String msg = String.format("type:%s, event:%s, key:%s",
                wxMessage.getMsgType(), wxMessage.getEvent(),
                wxMessage.getEventKey());

        //获取发送方OPENID
        String fromUserOpenId = wxMessage.getFromUser();
        log.info("[MenuClickFromUserOpenId] = " + fromUserOpenId);

//        log.info("*****[MenuHandler] ="
//                +"__getContent__" +wxMessage.getContent()
//                        +"__getEvent__"  +wxMessage.getEvent()
//                        +"__getEventKey__" +wxMessage.getEventKey()
//                        +"__getMsg__" +wxMessage.getMsg()
//                        +"__getMsgType__" +wxMessage.getMsgType()
//                        +"__getMenuId__" +wxMessage.getMenuId()
//                        +"__getMsgId__" +wxMessage.getMsgId());

        UserInfo userInfo = userInfoService.getUserBaseInfoByOpenId(fromUserOpenId);

        if (userInfo == null) {
            return null;
        }

        WeixinServiceDL weixinService = (WeixinServiceDL) wxMpService;
        PlatformSysInfo platformSysInfoConfig = sysGzhService.getPlatformSysInfoByAppId(weixinService.getWxMpConfigStorage().getAppId());



        if (WxConsts.EventType.CLICK.equals(wxMessage.getEvent())) {

            String eventKey = wxMessage.getEventKey();

            if ("V1001_GENETRATE_DISCOUNT".equals(eventKey)) {

                return generateDiscountPushMsg(wxMessage.getFromUser(), weixinService);

            } else if ("V1001_GENERATE_PROMOTE".equals(eventKey)) {

                return generatePromotePushMsg(wxMessage, wxMessage.getFromUser(), userInfo, weixinService, platformSysInfoConfig);

            } else if ("V1002_GET_NETWORK".equals(eventKey)) {

                return generateNetworkPushMsg(userInfo, wxMessage.getFromUser(), weixinService, platformSysInfoConfig, 0);

            } else if ("V1003_CLASS_MANAGEMENT".equals(eventKey)) {

                return pushMsg(SysConstant.CLICK_CLASS_MANAGEMENT_PUSH_MSG, wxMessage.getFromUser(), weixinService);

            } else if (SysConstant.V1003_CLASS_KEFU.equals(eventKey)) {//金钻客服
                msgHandler.returnKF(weixinService, wxMessage.getFromUser(), platformSysInfoConfig);
            } else if (SysConstant.V1003_CLASS_KEFU2.equals(eventKey)) {//客服
                mySendKefuMessage_ChangHui(wxMessage, weixinService, platformSysInfoConfig);
            } else if (SysConstant.ADD_ARTICLE_VIDEO.equals(eventKey)) {//添加文章或视频
                mySendMessageAddArticleVideo(wxMessage, weixinService, platformSysInfoConfig);
            } else if ("GOTO_KHZZZS".equals(eventKey)) {//引流到 客户追踪助手
                goto_zgts(wxMessage, weixinService, platformSysInfoConfig);
            }else if (SysConstant.V1004_CLASS_PUNCH_CLOCK.equals(eventKey)) {//早晚安打卡
                mySendKefuMessagePunchClock(wxMessage, weixinService,userInfo);
            }

            if (!eventKey.equals("V1001_GENERATE_PROMOTE")) {
                //region 如果用户是点击回复,10秒给他推送提醒 20210908
                try {
                    //msgHandler.mySendKefuMessage_10sec(wxMessage, weixinService, userInfo,platformSysInfoConfig.getSysGzh().getGzhCode());
                    sendkefuMsgAsyncTask.send10secKefuMsg(userInfo,platformSysInfoConfig,10000);
                }catch (Exception e) {}
                //endregion
            }

            return null;
        }

        if (WxConsts.EventType.VIEW.equals(wxMessage.getEvent())) {

            String eventKey = wxMessage.getEventKey();

            //如果点击了客户链接，则缓存相关信息
            if (eventKey.contains("member-page")) {

                WxPushUserInfo wxPushUserInfo = new WxPushUserInfo();
                wxPushUserInfo.setUserId(userInfo.getUserId());
                wxPushUserInfo.setOpenId(fromUserOpenId);
                wxPushUserInfo.setCacheTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
                redisCacheUtil.setCacheObject("customerPageWxPushUser" + userInfo.getUserId(), JSON.toJSONString(wxPushUserInfo), 2592000);

            }

            //log.error("MenuHandler ***  eventKey:"+eventKey);
            if (!eventKey.contains("pages/setting/member.html")) {
                //region 如果用户是点击回复,10秒给他推送提醒 20210908
                try {
                    //msgHandler.mySendKefuMessage_10sec(wxMessage, weixinService, userInfo,platformSysInfoConfig.getSysGzh().getGzhCode());
                    sendkefuMsgAsyncTask.send10secKefuMsg(userInfo,platformSysInfoConfig,10000);
                }catch (Exception e) {}
                //endregion
            }

            return null;
        }

        return WxMpXmlOutMessage.TEXT().content(msg)
                .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                .build();
    }

    private WxMpXmlOutMessage generatePromotePushMsg(WxMpXmlMessage wxMessage, String toUser, UserInfo userInfo, WeixinServiceDL weixinService, PlatformSysInfo platformSysInfoConfig) {

        try {
            String msg=SysConstant.CLICK_PROMOTE_MENU_PUSH_MSG2.replace(SysConstant.frontDomain, platformSysInfoConfig.getFrontDomain());

            if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                msg =ToolUtil.handleMsgmenuidByIOS(msg);
            }

            WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(toUser).content(msg).build();
            weixinService.getKefuService().sendKefuMessage(message);

            WxMpQrCodeTicket ticket = weixinService.getQrcodeService().qrCodeCreateTmpTicket(userInfo.getUserId(), 2592000);
            File qrCodePictureFile = weixinService.getQrcodeService().qrCodePicture(ticket);

            //商务合作链接
//            WxMpKefuMessage busMessage = WxMpKefuMessage.TEXT().toUser(toUser).content(SysConstant.WX_USER_BUS_COOP_PUSH_MSG).build();
//            weixinService.getKefuService().sendKefuMessage(busMessage);

            //下载用户头像
            String avatarName = UUID.randomUUID().toString() + ".jpg";
            ToolUtil.downloadAvatarPic(userInfo.getAvatarUrl(), userInfo.getUserId(), avatarName);

            String avatarPath = SysConstant.WX_AVATAR_DOWNLOAD_PATH + userInfo.getUserId() + "/" + avatarName;

            String qrCodePath = qrCodePictureFile.getAbsolutePath();

            String validTime = "二维码有效期至" + DateUtil.getFormatDate("yyyy年MM月dd日", DateTime.now().plusDays(30));

            //File resultImg = SharedImageUtils.generateSharedImage(avatarPath, qrCodePath, userInfo.getNickName(), validTime,wxShareImgPath);
            File resultImg = SharedImageUtils.generateSharedImage(avatarPath, qrCodePath, userInfo.getNickName(), validTime, platformSysInfoConfig.getWxShareImgPath(), platformSysInfoConfig.getSysGzh().getGzhCode());


            WxMediaUploadResult wxMediaUploadResult = weixinService.getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, resultImg);

            String mediaId = wxMediaUploadResult.getMediaId();

            return new ImageBuilder().build(mediaId, wxMessage, weixinService);

        } catch (WxErrorException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

    private WxMpXmlOutMessage generateDiscountPushMsg(String toUser, WeixinServiceDL weixinService) {

        try {

            String msg=SysConstant.CLICK_DISCOUNT_MENU_PUSH_MSG;

            UserInfo userInfo = userInfoService.getUserBaseInfoByOpenId(toUser);
            if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                msg =ToolUtil.handleMsgmenuidByIOS(msg);
            }

            WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(toUser).content(msg).build();
            weixinService.getKefuService().sendKefuMessage(message);

        } catch (WxErrorException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

    //发送内容
    //@Async
    @Async("taskExecutor")
    public WxMpXmlOutMessage pushMsg(String msg, String toUser, WxMpService weixinService) {

        try {

            UserInfo userInfo = userInfoService.getUserBaseInfoByOpenId(toUser);
            if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                msg =ToolUtil.handleMsgmenuidByIOS(msg);
            }

            WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(toUser).content(msg).build();
            weixinService.getKefuService().sendKefuMessage(message);

        } catch (WxErrorException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Async
    public WxMpXmlOutMessage generateNetworkPushMsg(UserInfo userInfo, String toUser, WxMpService weixinService, PlatformSysInfo platformSysInfo, long sleepCount) {

        try {
            Thread.sleep(30000 + sleepCount);

            SysGzh sysGzh = platformSysInfo.getSysGzh();
            String springProfilesActive = sysGzh.getGzhCode();
            String wxShareImgPath = platformSysInfo.getWxShareImgPath();

            String NETWORKPUSH_MSG = SysConstant.NETWORKPUSH_MSG.replace("[username]", userInfo.getNickName());

            //20210120 合作号、特价号 不搞活动
            if (!springProfilesActive.equalsIgnoreCase("prodjzyxt") &&
                    !springProfilesActive.equalsIgnoreCase("prodjpsj") &&
                    !springProfilesActive.equalsIgnoreCase("proddsk") &&
                    !springProfilesActive.equalsIgnoreCase("prodbdxzs") &&
                    !springProfilesActive.equalsIgnoreCase("prodxscja")  ) {

                String isActivity = messageDictInfoService.getConfigValueByKey(SysConstant.IsActivity);
                if (isActivity.equals("1")) {
                    NETWORKPUSH_MSG = NETWORKPUSH_MSG + "\n\t" +
                            messageDictInfoService.getLinkMsgByKey(SysConstant.SUBSCRIBE_A, platformSysInfo.getFrontDomain(), platformSysInfo.getOpenMemberMenuUrl());
                }
            }

            if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                NETWORKPUSH_MSG =ToolUtil.handleMsgmenuidByIOS(NETWORKPUSH_MSG);
            }

            WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(toUser).content(NETWORKPUSH_MSG).build();
            weixinService.getKefuService().sendKefuMessage(message);

            Thread.sleep(100);
            //String clickSendImg = SysConstant.WX_SHARE_IMG_PATH + "getNetwork.png";

            // 推送客服二维码
            /** 20201222 ljt start*/
            generalKeFuQrCodePushMsg(toUser, weixinService, platformSysInfo);
            /** 20201222 ljt end*/

        } catch (WxErrorException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    //@Async
    @Async("taskExecutor")
    public WxMpXmlOutMessage getProfessionalPushMsg(UserInfo userInfo, String toUser, WxMpService weixinService, PlatformSysInfo platformSysInfo, long sleepCount) {

        try {
            Thread.sleep(60000);
            //Thread.sleep(20000);

            SysGzh sysGzh = platformSysInfo.getSysGzh();
            String springProfilesActive = sysGzh.getGzhCode();
            String wxShareImgPath = platformSysInfo.getWxShareImgPath();

            String NETWORKPUSH_MSG = SysConstant.NETWORKPUSH_MSG_PROFESSIONAL.replace("[username]", userInfo.getNickName());

            if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                NETWORKPUSH_MSG =ToolUtil.handleMsgmenuidByIOS(NETWORKPUSH_MSG);
            }

            WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(toUser).content(NETWORKPUSH_MSG).build();
            weixinService.getKefuService().sendKefuMessage(message);

            Thread.sleep(100);
            /** 20201222 ljt start*/
            generalKeFuQrCodePushMsg(toUser, weixinService, platformSysInfo);
            /** 20201222 ljt end*/

        } catch (WxErrorException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }



    //@Async
    @Async("taskExecutor")
    public WxMpXmlOutMessage professionalToolsPushMsg(UserInfo userInfo, String toUser, WxMpService weixinService, PlatformSysInfo platformSysInfo, long sleepCount) {

        try {
            Thread.sleep(1000 + sleepCount);
            //Thread.sleep(60000);

            String profile=platformSysInfo.getSysGzh().getGzhCode();

            ArticleInfo article= null;

            if (profile != null && profile.equals("prodzx1")) {//装小编
                article=articleInfoService.getArticleDetailByInfo(null);
            } else if (profile != null && (profile.equals("prodhyxt") || profile.equals("prodhysck"))) { //护眼学堂
                article=articleInfoService.getArticleDetailByInfo(5948579);
            } else if (profile != null && (profile.equals("prodshjj") || profile.equals("prodshsck"))) { //私护之家
                article=articleInfoService.getArticleDetailByInfo(5948415);
            } else if (profile != null && profile.equals("prodbkwz")) { //鼻康微站
                article=articleInfoService.getArticleDetailByInfo(5925548);
            }

            WxMpKefuMessage.WxArticle wxArticle = new WxMpKefuMessage.WxArticle();
            wxArticle.setTitle(article.getArticleTitle());
            wxArticle.setDescription(article.getArticleDesc());
            wxArticle.setPicUrl(article.getArticleImgUrl()+"?"+SysConstant.OSS_PAR_80_80);
            wxArticle.setUrl(platformSysInfo.getArticleDetailUrl() + article.getId());

            WxMpKefuMessage testMsg = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(toUser).build();
            weixinService.getKefuService().sendKefuMessage(testMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Async
    public WxMpXmlOutMessage generateToolsPushMsg(UserInfo userInfo, String toUser, WxMpService weixinService, PlatformSysInfo platformSysInfo, long sleepCount) {

        try {
            Thread.sleep(1000*180);//3分钟

            Map<Integer, ToolsInfo> tools = getToolsMsg();
            List<UserBrandCombinedInfo> userBrands = userBrandInfoService.getUserBrandInfo(userInfo.getUserId());

            for (UserBrandCombinedInfo ub : userBrands) {
                if (tools.containsKey(ub.getBrandId())) {

                    ToolsInfo t= tools.get(ub.getBrandId());

                    WxMpKefuMessage.WxArticle wxArticle = new WxMpKefuMessage.WxArticle();
                    wxArticle.setTitle(t.getTitle());
                    wxArticle.setDescription(t.getRemarks());
                    wxArticle.setPicUrl(t.getImgUrl());
                    wxArticle.setUrl(platformSysInfo.getMyBrandsUrl()+"&brandId="+t.getId());

                    WxMpKefuMessage testMsg = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(toUser).build();
                    weixinService.getKefuService().sendKefuMessage(testMsg);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    @Async
    public WxMpXmlOutMessage headMsgPushMsg(UserInfo userInfo, String toUser, WxMpService weixinService, PlatformSysInfo platformSysInfoConfig) {

        try {

            Thread.sleep(2000);

            WxMpKefuMessage.WxArticle wxArticle = new WxMpKefuMessage.WxArticle();
            wxArticle.setTitle("点击领取你的国庆专属头像吧！");
            wxArticle.setDescription("多款国庆头像免费制作～");
            //wxArticle.setPicUrl(generateMessagePicUrl);
            wxArticle.setPicUrl(platformSysInfoConfig.getGenerateMessagePicUrl());

            //"https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/b9.png"
            //拼接链接地址
            //String articleDetailUrl = platformSysInfoConfig.getFrontDomain();
            //String accessUrl = articleDetailUrl + "/pages/setting/makeHeadPortrait.html";
            String accessUrl = platformSysInfoConfig.getHeadSculptureMenuUrl();

            wxArticle.setUrl(accessUrl);
            WxMpKefuMessage testMsg = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(toUser).build();

            weixinService.getKefuService().sendKefuMessage(testMsg);

            //String clickSendImg = wxShareImgPath  + "campaignPoster2.png";
            String clickSendImg = platformSysInfoConfig.getWxShareImgPath() + "campaignPoster2.png";

            //String clickSendImg = wxShareImgPath + "getNetwork.png";
            File resultImg = new File(clickSendImg);

            WxMediaUploadResult wxMediaUploadResult = weixinService.getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, resultImg);

            String mediaId = wxMediaUploadResult.getMediaId();

            if (StringUtils.isNotBlank(mediaId)) {

                WxMpKefuMessage messageTwo = WxMpKefuMessage.IMAGE().toUser(toUser).mediaId(mediaId).build();
                weixinService.getKefuService().sendKefuMessage(messageTwo);

            }

        } catch (WxErrorException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Async
    public WxMpXmlOutMessage extensionMsgPush(String toUser, WxMpService weixinService, PlatformSysInfo platformSysInfoConfig) {
        try {
            Thread.sleep(2000);

            WxMpKefuMessage.WxArticle wxArticle = new WxMpKefuMessage.WxArticle();
            wxArticle.setTitle("【商机2020】有鱼是什么？为什么老板们都加入...");
            wxArticle.setDescription("消费变投资，导师免费带你启动新零售事业！");
            wxArticle.setPicUrl("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/zhaoshang.png");

            //"https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/b9.png"
            //拼接链接地址
            //   String articleDetailUrl = platformSysInfoConfig.getCanvassBusinessOrdersMenuUrl();
            String accessUrl = platformSysInfoConfig.getCanvassBusinessOrdersMenuUrl();

            wxArticle.setUrl(accessUrl);
            WxMpKefuMessage testMsg = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(toUser).build();
            weixinService.getKefuService().sendKefuMessage(testMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Async
    public WxMpXmlOutMessage exteMsgPush5(String toUser, WxMpService weixinService, PlatformSysInfo platformSysInfoConfig) {
        try {
            Thread.sleep(2000);

            WxMpKefuMessage.WxArticle wxArticle = new WxMpKefuMessage.WxArticle();
            wxArticle.setTitle("欧俪雅新品发布邀请函");
            wxArticle.setDescription("欧俪雅BF品牌新品发布邀请函");
            wxArticle.setPicUrl("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/zhaoshang2.png");

            //"https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/b9.png"
            //拼接链接地址
            //   String articleDetailUrl = platformSysInfoConfig.getCanvassBusinessOrdersMenuUrl();
            String accessUrl = platformSysInfoConfig.getCanvassBusinessOrdersMenuUrl();

            wxArticle.setUrl(accessUrl);
            WxMpKefuMessage testMsg = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(toUser).build();
            weixinService.getKefuService().sendKefuMessage(testMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 消息推送
     * yl 20200710
     *
     * @param toUser
     * @param weixinService
     * @return
     */
    @Async
    public WxMpXmlOutMessage exteMsgPush6(String toUser, WxMpService weixinService, PlatformSysInfo platformSysInfoConfig) {
        try {
            Thread.sleep(2000);

            WxMpKefuMessage.WxArticle wxArticle = new WxMpKefuMessage.WxArticle();
            wxArticle.setTitle("【商机2020】采源宝是什么？为什么老板们都加入？如何开...");
            wxArticle.setDescription("阿里巴巴聚力扶持，导师免费带你启动新零售事业！");
            wxArticle.setPicUrl("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/zhaoshang3.png");

            //"https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/b9.png"
            //拼接链接地址
            //   String articleDetailUrl = platformSysInfoConfig.getCanvassBusinessOrdersMenuUrl();
            String accessUrl = platformSysInfoConfig.getFrontDomain() + "/pages/officialAccounts/cybAttractInvestment.html";

            wxArticle.setUrl(accessUrl);
            WxMpKefuMessage testMsg = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(toUser).build();
            weixinService.getKefuService().sendKefuMessage(testMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 消息推送
     * hyl 20200819
     *
     * @param toUser
     * @param weixinService
     * @return
     */
    @Async
    public WxMpXmlOutMessage exteMsgPush7(String toUser, WxMpService weixinService, PlatformSysInfo platformSysInfoConfig) {
        try {
            Thread.sleep(2000);

            WxMpKefuMessage.WxArticle wxArticle = new WxMpKefuMessage.WxArticle();
            wxArticle.setTitle("【商机2020】聚多佳品是什么？为什么老板们都加入？如何开通？");
            wxArticle.setDescription("PDD社交电商平台，导师免费带你享财富盛宴！");
            wxArticle.setPicUrl("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/zhaoshang4.png");

            //"https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/b9.png"
            //拼接链接地址
            //   String articleDetailUrl = platformSysInfoConfig.getCanvassBusinessOrdersMenuUrl();
            String accessUrl = platformSysInfoConfig.getFrontDomain() + "/pages/officialAccounts/pinduoduo.html";

            wxArticle.setUrl(accessUrl);
            WxMpKefuMessage testMsg = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(toUser).build();
            weixinService.getKefuService().sendKefuMessage(testMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 消息推送
     * hyl 20200825
     *
     * @param toUser
     * @param weixinService
     * @return
     */
    @Async
    public WxMpXmlOutMessage exteMsgPush8(String toUser, WxMpService weixinService, PlatformSysInfo platformSysInfoConfig) {
        try {
            Thread.sleep(2000);

            WxMpKefuMessage.WxArticle wxArticle = new WxMpKefuMessage.WxArticle();
            wxArticle.setTitle("【拼多多新项目】根红苗正，王炸级项目！好货内购是什么？市场补贴20亿，对标天猫？");
            wxArticle.setDescription("拼多多社交电商平台，导师免费带你享财富盛宴！");
            wxArticle.setPicUrl("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/zhaoshang5.png");

            //"https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/b9.png"
            //拼接链接地址
            //   String articleDetailUrl = platformSysInfoConfig.getCanvassBusinessOrdersMenuUrl();
            String accessUrl = platformSysInfoConfig.getFrontDomain() + "/pages/officialAccounts/haohuoneigou.html";

            wxArticle.setUrl(accessUrl);
            WxMpKefuMessage testMsg = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(toUser).build();
            weixinService.getKefuService().sendKefuMessage(testMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 作品案例消息推送
     * ljt 20201013
     *
     * @param toUser
     * @param weixinService
     * @return
     */
    @Async
    public WxMpXmlOutMessage exteMsgPush9(String toUser, Integer fitId, WxMpService weixinService, PlatformSysInfo platformSysInfoConfig) {
        try {
            Thread.sleep(2000);

            BDecorationArticles bDecorationArticles = this.bDecorationArticlesService.queryById(fitId);

            String coverPlan = bDecorationArticles.getCoverPlan();//作品封面
            String headLine = bDecorationArticles.getHeadLine();//作品标题
            String worksIntroduce = bDecorationArticles.getWorksIntroduce();//作品介绍
            Integer autoUserId = bDecorationArticles.getUserId();//作者UserId

            UserInfo userInfo = this.userInfoService.getUserBaseInfo(autoUserId);

            String userNickName = userInfo.getNickName() + "的设计案例！";//作者昵称

            WxMpKefuMessage.WxArticle wxArticle = new WxMpKefuMessage.WxArticle();

            wxArticle.setTitle(headLine);
            wxArticle.setDescription(userNickName);
            wxArticle.setPicUrl(coverPlan);

            //"https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/b9.png"
            //拼接链接地址
            //   String articleDetailUrl = platformSysInfoConfig.getCanvassBusinessOrdersMenuUrl();
            String accessUrl = platformSysInfoConfig.getFrontDomain() + "/pages/fitment/showfitment.html?userId=" + autoUserId + "&id=" + fitId;

            wxArticle.setUrl(accessUrl);
            WxMpKefuMessage testMsg = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(toUser).build();

            weixinService.getKefuService().sendKefuMessage(testMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 商学院关注消息推送
     * ljt 20201208
     *
     * @param toUser
     * @param weixinService
     * @return
     */
    @Async
    public WxMpXmlOutMessage exteMsgPush10(String toUser, Integer fitId, WxMpService weixinService, PlatformSysInfo platformSysInfoConfig) {
        try {
            Thread.sleep(2000);

            BBusinessInfo bBusinessInfo = this.bBusinessInfoService.queryById(fitId);

            String coverPlan = bBusinessInfo.getCover();//商学院封面
            String headLine = bBusinessInfo.getTitle();//商学院标题
            String worksIntroduce = bBusinessInfo.getContent();//商学院介绍

            WxMpKefuMessage.WxArticle wxArticle = new WxMpKefuMessage.WxArticle();

            wxArticle.setTitle(headLine);
            wxArticle.setDescription(worksIntroduce);
            wxArticle.setPicUrl(coverPlan);

            String accessUrl = platformSysInfoConfig.getFrontDomain() + "/pages/setting/courseDetails.html?id=" + fitId;

            wxArticle.setUrl(accessUrl);
            WxMpKefuMessage testMsg = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(toUser).build();

            weixinService.getKefuService().sendKefuMessage(testMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 用户回复领取文章
     * hyl 20210618
     *
     * @param weixinService
     * @return
     */
    @Async
    public WxMpXmlOutMessage receiveArticle(UserInfo userInfo, WxMpService weixinService, PlatformSysInfo platformSysInfoConfig) {
        try {

            Object articleId = redisCacheUtil.getCacheObject("UPLOAD_TEMP_MSG_PUSH" + userInfo.getUserId());
            if (null != articleId) {

                ArticleInfo articleInfo = articleInfoService.getArticleDetailInfo((Integer) articleId);
                if (articleInfo != null) {

                    WxMpKefuMessage.WxArticle wxArticle = new WxMpKefuMessage.WxArticle();

                    wxArticle.setTitle(articleInfo.getArticleTitle());
                    wxArticle.setDescription(articleInfo.getArticleDesc());
                    wxArticle.setPicUrl(articleInfo.getArticleImgUrl()+"?"+SysConstant.OSS_PAR_80_80);

                    String accessUrl = platformSysInfoConfig.getShareDomainUrl() + "pages/article/detail.html?articleId=" + articleId + "&t=2"+"&userId="+userInfo.getUserId();

                    if (articleInfo.getResourceType().equals(2)) {//如果是视频
                        accessUrl = accessUrl.replace("/article/", "/video/");
                        accessUrl = accessUrl.replace("/detail.html?", "/index.html?");
                    }

                    wxArticle.setUrl(accessUrl);

                    WxMpKefuMessage testMsg = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(userInfo.getOpenId()).build();

                    weixinService.getKefuService().sendKefuMessage(testMsg);
                    redisCacheUtil.removeSingleCache("UPLOAD_TEMP_MSG_PUSH" + userInfo.getUserId());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //@Async
    @Async("taskExecutor")
    public WxMpXmlOutMessage pushSubscribeMsg(UserInfo userInfo, WxMpXmlMessage wxMessage, WxMpService weixinService, PlatformSysInfo platformSysInfoConfig, String springProfilesActive, long sleepCount) {
        try {
            Thread.sleep(sleepCount);

            String msg;
            if (springProfilesActive.equalsIgnoreCase("prodzx1") ||
                    springProfilesActive.equalsIgnoreCase("prodhyxt") ||
                    springProfilesActive.equalsIgnoreCase("prodhysck") ||
                    springProfilesActive.equalsIgnoreCase("prodshjj") ||
                    springProfilesActive.equalsIgnoreCase("prodshsck") ||
                    springProfilesActive.equalsIgnoreCase("prodbkwz")
            ) {  //专业号

                String gzhTitleStr = "";
                String gzhLet = "";

                if (springProfilesActive.equals("prodzx1")) {//装小编
                    gzhTitleStr = "⭕ 装小编，装修建材人的智能获客助手！";
                    gzhLet = "装修";
                } else if (springProfilesActive.equals("prodshjj") || springProfilesActive.equals("prodshsck")) { //私护之家
                    gzhTitleStr = "⭕ 私护之家，一个两性生殖健康知识、获客成长平台！";
                    gzhLet = "私护";
                } else if (springProfilesActive.equals("prodhyxt") || springProfilesActive.equals("prodhysck")) { //护眼
                    gzhTitleStr = "⭕ 护眼学堂，一个科普爱眼、护眼知识，智能获客平台。";
                    gzhLet = "护眼";
                } else if (springProfilesActive.equals("prodbkwz")) { //鼻康微站
                    gzhTitleStr = "⭕ 鼻康微站，一个分享鼻腔、鼻炎健康，打造专业人设平台！";
                    gzhLet = "鼻康";
                } else if (springProfilesActive.equals("back_zkt")) { //鼻康微站
                    gzhTitleStr = "⭕ 鼻康微站，一个分享鼻腔、鼻炎健康，打造专业人设平台！";
                    gzhLet = "鼻康";
                }
                msg = SysConstant.SUBSCRIBE_PUSH_MSG_ZHUANGXIAOBIAN
                        .replace(SysConstant.gzhTitleStr, gzhTitleStr)
                        .replace(SysConstant.gzhLetStr, gzhLet)
                        .replace("[username]", userInfo.getNickName() == null ? "" : userInfo.getNickName())
                        .replace(SysConstant.frontDomain, platformSysInfoConfig.getFrontDomain());
                ;
            } else {
                msg = SysConstant.SUBSCRIBE_PUSH_MSG_KEYWORK
                        .replace("[username]", userInfo.getNickName() == null ? "" : userInfo.getNickName())
                        .replace("[userid]", userInfo.getUserId() == null ? "0" : userInfo.getUserId().toString())
                        .replace(SysConstant.gzhNameStr, platformSysInfoConfig.getSysGzh().getGzhName())
                        .replace(SysConstant.frontDomain, platformSysInfoConfig.getFrontDomain());
            }

            // yl end 20200704
            if (springProfilesActive != null) {
                msg = msg.replace(SysConstant.gzhNameStr, platformSysInfoConfig.getSysGzh().getGzhName());
            }

            if (userInfo.getPhoneModel().equals(SysConstant.IOS)) {
                msg = ToolUtil.handleMsgmenuidByIOS(msg);
            }

            mySendKefuMessage(wxMessage, weixinService, msg, 0);
            //new TextBuilder().build(msg, wxMessage, weixinService);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 新关注推送优惠券
     * hyl 20200810
     *
     * @param toUser
     * @param weixinService
     * @return
     */
    @Async
    public WxMpXmlOutMessage pushCoupon(String toUser, WxMpService weixinService, PlatformSysInfo platformSysInfoConfig, long sleepCount) {
        try {
            Thread.sleep(1000 + sleepCount);

            WxMpKefuMessage.WxArticle wxArticle = new WxMpKefuMessage.WxArticle();
            String springProfilesActive = platformSysInfoConfig.getSysGzh().getGzhCode();

            //合作号 不搞活动
            if (springProfilesActive.equalsIgnoreCase("prodjzyxt") ||
                    springProfilesActive.equalsIgnoreCase("prodjpsj") ||
                    springProfilesActive.equalsIgnoreCase("proddsk") ||
                    springProfilesActive.equalsIgnoreCase("prodbdxzs") ) {
                wxArticle.setTitle("[红包]新人专属30元优惠券");//平时
            } else {

                String wxArticleTitle = "";

                String isActivity = messageDictInfoService.getConfigValueByKey(SysConstant.IsActivity);
                if (isActivity.equals("1")) {//搞活动时
                    MessageDictInfo messageDictRed_A = messageDictInfoService.getInfoByKey(SysConstant.RED_A);
                    if (messageDictRed_A != null) {
                        wxArticleTitle = messageDictRed_A.getDictVal();
                    }
                } else {//平时
                    MessageDictInfo messageDictRed = messageDictInfoService.getInfoByKey(SysConstant.RED);
                    if (messageDictRed != null) {
                        wxArticleTitle = messageDictRed.getDictVal();
                    }
                }
                wxArticle.setTitle(wxArticleTitle);
            }

            wxArticle.setDescription("点击领取>>>");//平时
            wxArticle.setPicUrl("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/couponLogo.jpg");//平时

//            wxArticle.setDescription("错过后悔一年，点我领取>>");//618
//            wxArticle.setPicUrl("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/couponLogo618.jpg");//618

            //拼接链接地址
            //   String articleDetailUrl = platformSysInfoConfig.getCanvassBusinessOrdersMenuUrl();
            String accessUrl = platformSysInfoConfig.getOpenMemberMenuUrl() + "?mt=1&cardBag=1";

            wxArticle.setUrl(accessUrl);
            WxMpKefuMessage testMsg = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(toUser).build();
            weixinService.getKefuService().sendKefuMessage(testMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //@Async
    @Async("taskExecutor")
    public WxMpXmlOutMessage pushCouponProfessionalNew(UserInfo userInfo, WxMpXmlMessage wxMessage, WxMpService weixinService, PlatformSysInfo platformSysInfoConfig, long sleepCount) {
        try {
            Thread.sleep(sleepCount);
            String msg = "\uD83D\uDC51尊敬的" + userInfo.getNickName() + "，您的超值代金券已生效\n\n" +
                    "\uD83D\uDC49<a href=\"weixin://bizmsgmenu?msgmenucontent=领取优惠&msgmenuid=+++\">请立即前往领取>></a>\n\n" +
                    "\uD83C\uDF89<a href=\"weixin://bizmsgmenu?msgmenucontent=神秘礼品&msgmenuid=+++\">首次开通会员还能领礼包哦？[跳跳]点这里查看神秘礼品</a>";

            mySendKefuMessage(wxMessage, weixinService, msg, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //@Async
    @Async("taskExecutor")
    public WxMpXmlOutMessage pushCouponProfessional(String toUser, WxMpService weixinService, PlatformSysInfo platformSysInfoConfig, long sleepCount) {
        try {
            Thread.sleep(sleepCount);

            WxMpKefuMessage.WxArticle wxArticle = new WxMpKefuMessage.WxArticle();

            //合作号 不搞活动

            String wxArticleTitle = "";

            String isActivity = messageDictInfoService.getConfigValueByKey(SysConstant.IsActivity);
            if (isActivity.equals("1")) {//搞活动时
                MessageDictInfo messageDictRed_A = messageDictInfoService.getInfoByKey(SysConstant.RED_P_A);
                if (messageDictRed_A != null) {
                    wxArticleTitle = messageDictRed_A.getDictVal();
                }
            } else {//平时
                MessageDictInfo messageDictRed = messageDictInfoService.getInfoByKey(SysConstant.RED_A);
                if (messageDictRed != null) {
                    wxArticleTitle = messageDictRed.getDictVal();
                }
            }
            wxArticle.setTitle(wxArticleTitle);

            //平时
            wxArticle.setDescription("点击速抢》》");
            wxArticle.setPicUrl("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/couponLogo2.png");
            //wxArticle.setPicUrl("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/couponLogoZhongQiu.png");

            String accessUrl = platformSysInfoConfig.getOpenMemberMenuUrl() + "?mt=1&cardBag=1";

            wxArticle.setUrl(accessUrl);
            WxMpKefuMessage testMsg = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(toUser).build();
            weixinService.getKefuService().sendKefuMessage(testMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 新关注推送赠送vip
     * hyl 20200901
     *
     * @param userId
     * @param platformSysInfoConfig
     * @return
     */
    //@Async
    @Async("taskExecutor")
    public WxMpXmlOutMessage pushGiveVip(Integer userId, PlatformSysInfo platformSysInfoConfig, long sleepCount) {
        try {
            Thread.sleep(1000 * 3600);//1个小时

            String springProfilesActive = platformSysInfoConfig.getSysGzh().getGzhCode();

            Map<String, String> headMap = Maps.newHashMap();
            headMap.put("userId", userId.toString());
            headMap.put("profile", springProfilesActive);
            String finalReqUrl = platformSysInfoConfig.getTaskUrl() + "uploadMsgPush";
            HttpClientUtils.sendPost(finalReqUrl, headMap, Maps.newHashMap());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 3分钟后如果还没设置品牌，自动设置
     * hyl 20211109
     * @param springProfilesActive
     * @param finalUserId
     * @param sleepCount
     * @return
     */
    //@Async
    @Async("taskExecutor")
    public WxMpXmlOutMessage setBrand3Minutes(String springProfilesActive,Integer finalUserId, long sleepCount) {
        try {
            Thread.sleep(1000 * 60 * 3);//3分钟

            List<UserBrandCombinedInfo> userBrands = userBrandInfoService.getUserBrandInfo(finalUserId);
            if (userBrands == null || userBrands.size() <= 0) {//当前用户没有品牌
                userBrandInfoService.setDefaultBrand(springProfilesActive, finalUserId,1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 新关注推送开单页(金钻云学堂)
     * hyl 20200810
     *
     * @param toUser
     * @param weixinService
     * @return
     */
    @Async
    public WxMpXmlOutMessage pushOpenMemberMenuUrl_jzyxt(String toUser, WxMpService weixinService, PlatformSysInfo platformSysInfoConfig) {
        try {
            Thread.sleep(1000 * 60 * 30);//30分钟

            WxMpKefuMessage.WxArticle wxArticle = new WxMpKefuMessage.WxArticle();
            //wxArticle.setTitle("[红包]新人专属30元优惠券");平时
            wxArticle.setTitle("营养课程+销售课程+抖音课程+直播课程·8大课系即将开班，速速进课堂，不掉队！");
            wxArticle.setDescription("点击领取>>>");
            wxArticle.setPicUrl("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/jzyxt_hylb.png");

            String accessUrl = platformSysInfoConfig.getOpenMemberMenuUrl() + "?mt=1";

            wxArticle.setUrl(accessUrl);
            WxMpKefuMessage testMsg = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(toUser).build();
            weixinService.getKefuService().sendKefuMessage(testMsg);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Async
    public WxMpXmlOutMessage mySendKefuMessage_jzyxt(WxMpXmlMessage wxMessage, WeixinServiceDL weixinService, PlatformSysInfo platformSysInfoConfig) throws InterruptedException {
        Thread.sleep(1000 * 60 * 5);//5分钟

        String kefuMsg2 =
                "\uD83D\uDD38 领·完美产品大全\n" +
                        "\uD83D\uDD38 领·进阶课程课件\n" +
                        "\uD83D\uDD38 领·宣传营销海报\n\n" +
                        "\uD83D\uDC47 扫码添加云课堂讲师微信！金钻老师手把手教你讲产品、讲销售、讲观念";

        mySendKefuMessage(wxMessage, weixinService, kefuMsg2, 0);
        msgHandler.returnKF(weixinService, wxMessage.getFromUser(), platformSysInfoConfig);
        return null;
    }

    /**
     * 牛年推送
     * hyl 20210114
     *
     * @param wxMessage
     * @param weixinService
     * @return
     */
    @Async
    public WxMpXmlOutMessage setMostNationalDay(WxMpXmlMessage wxMessage, WxMpService weixinService, PlatformSysInfo platformSysInfoConfig) {
        try {
            //Thread.sleep(3000);

            String SEND_NATIONAL_DAY_PUSH_MSG = "<a href=\"" + platformSysInfoConfig.getHeadSculptureMenuUrl() + "\">✨领取更多国庆头像>></a>";

            UserInfo userInfo = userInfoService.getUserBaseInfoByOpenId(wxMessage.getFromUser());
            if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                SEND_NATIONAL_DAY_PUSH_MSG =ToolUtil.handleMsgmenuidByIOS(SEND_NATIONAL_DAY_PUSH_MSG);
            }

            WxMpKefuMessage messageDay = WxMpKefuMessage.TEXT().toUser(wxMessage.getFromUser()).content(SEND_NATIONAL_DAY_PUSH_MSG).build();
            weixinService.getKefuService().sendKefuMessage(messageDay);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //通用发送文字
    @Async
    public WxMpXmlOutMessage mySendKefuMessage(WxMpXmlMessage wxMessage, WxMpService weixinService, String kefuMsg, long millis) {
        try {
            Thread.sleep(millis);

            UserInfo userInfo = userInfoService.getUserBaseInfoByOpenId(wxMessage.getFromUser());
            if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                kefuMsg =ToolUtil.handleMsgmenuidByIOS(kefuMsg);
            }

            WxMpKefuMessage messageDay = WxMpKefuMessage.TEXT().toUser(wxMessage.getFromUser()).content(kefuMsg).build();
            weixinService.getKefuService().sendKefuMessage(messageDay);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //通用发送图片
    @Async
    public WxMpXmlOutMessage mySendKefuImg(WxMpXmlMessage wxMessage, WxMpService weixinService, String clickSendImg, long millis) {
        try {
            Thread.sleep(millis);

            File resultImg = new File(clickSendImg);

            WxMediaUploadResult wxMediaUploadResult = weixinService.getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, resultImg);

            String mediaId = wxMediaUploadResult.getMediaId();

            if (StringUtils.isNotBlank(mediaId)) {

                WxMpKefuMessage messageTwo = WxMpKefuMessage.IMAGE().toUser(wxMessage.getFromUser()).mediaId(mediaId).build();
                weixinService.getKefuService().sendKefuMessage(messageTwo);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Async
    public WxMpXmlOutMessage goto_zgts(WxMpXmlMessage wxMessage, WeixinServiceDL weixinService, PlatformSysInfo platformSysInfoConfig) {

//        Random random = new java.util.Random(); // 定义随机类
//        int num = random.nextInt(10);
//
//        String KEFU1_MSG =
//                "叮\uD83D\uDD14\n" +
//                        "您有一份客户大礼包\uD83C\uDF81尚未领取\n" +
//                        "关注【掌柜推手】添加客服领取\n" +
//                        "\uD83D\uDC47扫码关注\uD83D\uDC47";
//
//        String KEFU2_MSG =
//                "【重要通知】❗❗❗\n" +
//                        "小神吹之家平台维护升级中\n" +
//                        "关注新号【掌柜推手】接收素材\n" +
//                        "\uD83D\uDC47扫码关注\uD83D\uDC47";
//
//        String msg = "";
//        if (num % 2 == 0) {
//            msg = KEFU2_MSG;
//        } else {
//            msg = KEFU1_MSG;
//        }
//
//        mySendKefuMessage(wxMessage, weixinService, msg, 0);

        pushMsg("[握手] 您好，由于公众号升级，请关注新号继续使用\n\n<a href=\"weixin://bizmsgmenu?msgmenucontent=客服&msgmenuid=+++\">\uD83C\uDF37 有任何问题请回复【客服】解答</a>"
                , wxMessage.getFromUser(), weixinService);

        String[] gzhArr = {"kdbw_qrcode.png"};

        int index = (int) (Math.random() * gzhArr.length);

        String clickSendImg = platformSysInfoConfig.getWxShareImgPath() + gzhArr[index];
        mySendKefuImg(wxMessage, weixinService, clickSendImg, 0);

        return null;
    }

    @Async
    public WxMpXmlOutMessage mySendKefuMessage_ChangHui(WxMpXmlMessage wxMessage, WeixinServiceDL weixinService, PlatformSysInfo platformSysInfoConfig) {

        String KEFU2_MSG =
                "➜ <a href=\"" + platformSysInfoConfig.getCooperationUrl() + "\">合作/代理</a>\n\n" +
                        "➜ <a href=\"weixin://bizmsgmenu?msgmenucontent=推广赚钱&msgmenuid=+++\">推广赚钱</a>\n\n" +
                        "➜ <a href=\"" + platformSysInfoConfig.getFrontDomain() + "/pages/officialAccounts/IntroduceVideo.html\">产品介绍</a>\n\n" +
                        "➜ <a href=\"" + SysConstant.SUGGESTION_URL + "\">投诉建议</a>";

        mySendKefuMessage(wxMessage, weixinService, KEFU2_MSG, 0);
        msgHandler.returnKF(weixinService, wxMessage.getFromUser(), platformSysInfoConfig);
        return null;
    }

//    @Async
//    public WxMpXmlOutMessage mySendKefuMessage_10sec(WxMpXmlMessage wxMessage, WeixinServiceDL weixinService,UserInfo userInfo,String gzhCode) {
//
//        if (userInfo != null) {
//            int h = 24;
//            KeyWrodInfo keyWrodInfo = keywordDetailLogMapper.getLastKeyWord(gzhCode, userInfo.getUserId());
//
//            if (keyWrodInfo != null) {
//                h = DateUtil.getTimeDiff(3, keyWrodInfo.getCreateTime());
//            }
//
//            Object activeMsgPush = redisCacheUtil.getCacheObject("ACTIVE_10SEC_MSG_PUSH" + userInfo.getUserId());
//
//            if (activeMsgPush == null && h >= 24) {//一个小时内没发过，而且 距离上一次 输入回复已经有24小时
//                BrandInfo brandInfo = userBrandInfoService.getUserSelectBrandInfo(userInfo.getUserId());
//                if (brandInfo != null) {
//
//                    String KEFU2_MSG = SysConstant.WX_10SEC.replace("[username]", userInfo.getNickName())
//                            .replace("[brandName]", brandInfo.getBrandName());
//
//                    redisCacheUtil.setCacheObject("ACTIVE_10SEC_MSG_PUSH" + userInfo.getUserId(), 1, 3600);
//
//                    mySendKefuMessage(wxMessage, weixinService, KEFU2_MSG, 10000);
//
//                }
//            }
//        }
//        return null;
//    }

    @Async
    public WxMpXmlOutMessage mySendKefuMessage_huifujihuo(WxMpXmlMessage wxMessage, WeixinServiceDL weixinService,UserInfo userInfo) {


        BrandInfo brandInfo= userBrandInfoService.getUserSelectBrandInfo(userInfo.getUserId());

        if(userInfo!=null && brandInfo!=null) {

            String KEFU2_MSG =
                    "\uD83C\uDF39 " + userInfo.getNickName() + ",您好，由于微信公众号消息改版了，[可怜]所以需要您在公众号回复消息，才能激活推送功能，否则小编想给您推送文章却发不出去哦~\n\n[抱拳]您只需要按照提示，回复任意一个数字，就可以激活成功的~感谢！\n\n" +
                            "➜ <a href=\"weixin://bizmsgmenu?msgmenucontent=客户&msgmenuid=+++\">回复数字【 1 】追踪精准客户</a>\n\n" +
                            /*"➜ <a href=\"weixin://bizmsgmenu?msgmenucontent=人脉广场&msgmenuid=+++\">回复数字【 2 】加现成人脉聊</a>\n\n" +*/
                            "➜ <a href=\"weixin://bizmsgmenu?msgmenucontent=客服&msgmenuid=+++\">回复数字【 6 】找客服解疑</a>\n\n" +
                            "➜ <a href=\"weixin://bizmsgmenu?msgmenucontent=唤醒小编&msgmenuid=+++\">回复数字【 9 】更多"+brandInfo.getBrandName()+"爆文</a>";

            mySendKefuMessage(wxMessage, weixinService, KEFU2_MSG, 0);
        }
        return null;
    }

    @Async
    public WxMpXmlOutMessage mySendKefuMessagePunchClock(WxMpXmlMessage wxMessage, WeixinServiceDL weixinService,UserInfo userInfo) {

        Calendar rightNow = Calendar.getInstance();
        int hour = rightNow.get(Calendar.HOUR_OF_DAY);

        LocalDate now = LocalDate.now();

        Integer week = now.getDayOfWeek().getValue();
        String weekStr = "";
        switch (week) {
            case 1:
                weekStr = "星期一";
                break; //可选
            case 2:
                weekStr = "星期二";
                break; //可选
            case 3:
                weekStr = "星期三";
                break; //可选
            case 4:
                weekStr = "星期四";
                break; //可选
            case 5:
                weekStr = "星期五";
                break; //可选
            case 6:
                weekStr = "星期六";
                break; //可选
            case 7:
                weekStr = "星期天";
                break; //可选
            default: //可选
                weekStr = "";
        }

        String punchClock = "☀"+userInfo.getNickName()+" 老师，早上好！\n\n" +
                "今天是" + now.getYear() + "年" + now.getMonthValue() + "月" + now.getDayOfMonth() + "日 " + weekStr + "\n\n" +
                "\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=打卡&msgmenuid=+++\">点我生成早安播报，早安打卡</a>";
        if (hour > 16) {
            punchClock = userInfo.getNickName()+" 老师，晚上好！\n\n" +
                    "\uD83C\uDF1B 夜深了，跟朋友们道晚安吧！记得早点休息哦！\n\n" +
                    "\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=打卡&msgmenuid=+++\">点我生成晚安夜听，跟朋友道晚安吧！</a>";
        }

//        String punchClock =
//                "[拥抱]"+userInfo.getNickName()+"，与1000万人一起早晚安打卡吧~\n\n" +
//                        "\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=打卡&msgmenuid=+++\">回复数字【 7 】领取早晚安打卡</a>";
        mySendKefuMessage(wxMessage, weixinService, punchClock, 0);

        String custom =
                "⭕看您文章的客户都在这里哦\n\n" +
                        "\uD83D\uDC49 <a href=\"weixin://bizmsgmenu?msgmenucontent=客户&msgmenuid=+++\">点击查看《客户名单》</a>";
        mySendKefuMessage(wxMessage, weixinService, custom, 15000);

        return null;
    }

    @Async
    public WxMpXmlOutMessage mySendMessageAddArticleVideo(WxMpXmlMessage wxMessage, WeixinServiceDL weixinService, PlatformSysInfo platformSysInfoConfig) {
//
        /*String kefuMsg = "➜ <a href=\"" + platformSysInfoConfig.getFrontDomain() + "/pages/video/addVideo.html?v=90\">上传自己的视频</a>\n\n" +
                "➜ <a href=\"weixin://bizmsgmenu?msgmenucontent=快速添加文章与视频&msgmenuid=+++\">生成文章/视频</a>\n\n" +
                "➜ 快速添加方法\n\n" +
                "\uD83D\uDC47\uD83D\uDC47见下图";*/

        String kefuMsg = "➜ <a href=\"weixin://bizmsgmenu?msgmenucontent=快速添加文章&msgmenuid=+++\">生成文章</a>\n\n" +
                "➜ 快速添加方法\n\n" +
                "\uD83D\uDC47\uD83D\uDC47见下图";
        mySendKefuMessage(wxMessage, weixinService, kefuMsg, 0);

        String clickSendImg = platformSysInfoConfig.getWxShareImgPath() + "AddArticle.png";
        mySendKefuImg(wxMessage, weixinService, clickSendImg, 0);

        return null;
    }

    /**
     * 异步轮播推送客服二维码
     *
     * @param toUser
     * @param weixinService
     * @param platformSysInfo
     * @return
     */
    //@Async
    @Async("taskExecutor")
    public WxMpXmlOutMessage generalKeFuQrCodePushMsg(String toUser, WxMpService weixinService, PlatformSysInfo platformSysInfo) {
        try {
            Thread.sleep(2000);

            SysGzh sysGzh = platformSysInfo.getSysGzh();
            String springProfilesActive = sysGzh.getGzhCode();

            // 客服二维码
            String keFuQrCode = "";

            BMessageKefu bMessageKefu = new BMessageKefu();
            bMessageKefu.setGzhCode(springProfilesActive);

            List<BMessageKefu> list = bMessageKefuService.queryAll(bMessageKefu);
            if (CollectionUtils.isNotEmpty(list)) {
                Integer number = 0;
                Object kfImgNumberObj = redisCacheUtil.getCacheObject("kfImgNumber" + springProfilesActive);
                if (kfImgNumberObj != null) {
                    number = (Integer) kfImgNumberObj;
                    if (number > list.size() || number > (list.size() - 1)) {
                        number = 0;
                    }
                }
                redisCacheUtil.setCacheObject("kfImgNumber" + springProfilesActive, number + 1, 7200);
                keFuQrCode = list.get(number).getPicUrl();

                URL url = new URL(keFuQrCode);
                // 获取链接
                URLConnection conn = url.openConnection();
                // 输入流
                File targetFile = null;

                try (InputStream inStream = conn.getInputStream()) {
                    // 临时文件
                    targetFile = File.createTempFile(UUID.randomUUID().toString(), ".png");
//                    if(springProfilesActive.equals("prodhyxt")){
//                        System.out.println("prodhyxt:P:"+targetFile.toPath());
//                        System.out.println("prodhyxt:weixinService:"+weixinService.getWxMpConfigStorage().getAppId());
//                        System.out.println("prodhyxt:springProfilesActive:"+springProfilesActive);
//                    }
                    java.nio.file.Files.copy(inStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

                    WxMediaUploadResult wxMediaUploadResult = weixinService.getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, targetFile);

                    String mediaId = wxMediaUploadResult.getMediaId();

                    if (StringUtils.isNotBlank(mediaId)) {

                        WxMpKefuMessage messageTwo = WxMpKefuMessage.IMAGE().toUser(toUser).mediaId(mediaId).build();
                        weixinService.getKefuService().sendKefuMessage(messageTwo);

                    }
                } catch (IOException e) {
                    if(springProfilesActive.equals("prodhyxt")){
                        System.out.println("prodhyxt:E:"+e.getMessage());
                    }
                    e.printStackTrace();
                } finally {
                    // 在JVM退出时删除文件。也可以调用file.delete();立即删除文件。
                    targetFile.deleteOnExit();
                    // 删除临时文件
                    targetFile.delete();
                }
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private Map<Integer, ToolsInfo> getToolsMsg() {
        Map<Integer, ToolsInfo> toolsMsgs = Maps.newHashMap();
        ToolsInfo t1 = new ToolsInfo(28041, "奇易时光七大爆款产品大全", "立即领取>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/28041.png", "");
        ToolsInfo t2 = new ToolsInfo(33220, "虫草硒牡蛎钙近千个案例查看！", "立即领取>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/33220.png", "");
        ToolsInfo t3 = new ToolsInfo(36575, "共享村长项目资料【全员必读】", "立即查看>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/36575.png", "");
        ToolsInfo t4 = new ToolsInfo(37307, "华能最新资讯，家人们必看！", "立即查看>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/37307.png", "");
        ToolsInfo t5 = new ToolsInfo(36915, "【佛慈家人必看】最新肺部养护新爆文", "立即领取>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/36915.png", "");
        ToolsInfo t6 = new ToolsInfo(34667, "【最新】疆农源沙棘推广必备文章", "立即领取>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/34667.png", "");
        ToolsInfo t7 = new ToolsInfo(29720, "视频号保姆级教程", "立即领取>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/29720.png", "");
        ToolsInfo t8 = new ToolsInfo(40187, "【最新】倍善堂推广必备素材", "立即领取>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/40187.png", "");
        ToolsInfo t9 = new ToolsInfo(27336, "双迪无忧产品案例反馈", "立即查看>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/27336.png", "");
        ToolsInfo t10 = new ToolsInfo(23395, "玛咖产品案例资料必备大全！", "立即领取>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/23395.png", "");
        ToolsInfo t11 = new ToolsInfo(37568, "青青乐资料送到！请查收~", "立即查看>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/37568.png", "");
        ToolsInfo t12 = new ToolsInfo(38960, "黑金调理三高人群案例大全", "立即查看>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/38960.png", "");
        ToolsInfo t13 = new ToolsInfo(36552, "千亿口腔蓝海『完美大使』项目资料", "立即查看>>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/36552.png", "");
        ToolsInfo t14 = new ToolsInfo(67, "碧波庭调理案例资料大全", "立刻获取>>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/67.png", "");
        ToolsInfo t15 = new ToolsInfo(11408, "天赐竹盐资料大全、使用方法", "立刻获取>>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/11408.png", "");
        ToolsInfo t16 = new ToolsInfo(26977, "【易经风水】改运大全集合", "立刻领取秘籍", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/26977.png", "");
        ToolsInfo t17 = new ToolsInfo(10817, "【最新】光明推广必备资料大全", "立刻点击>>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/10817.png", "");
        ToolsInfo t18 = new ToolsInfo(35283, "【百德福海参肽】治愈疾病案例反馈", "点击进入>>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/35283.png", "");
        ToolsInfo t19 = new ToolsInfo(35168, "陆羽资料大全，请查收！", "点击进入>>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/35168.png", "");
        ToolsInfo t20 = new ToolsInfo(27506, "每日悠纤·NMN最全资料送到！", "立即查看>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/27506.png", "");
        ToolsInfo t21 = new ToolsInfo(37369, "【全员必看】社群共创操作流程大全！", "立即查看>>", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/brandImgs/37369.png", "");

        toolsMsgs.put(28041, t1);
        toolsMsgs.put(33220, t2);
        toolsMsgs.put(36575, t3);
        toolsMsgs.put(37307, t4);
        toolsMsgs.put(36915, t5);
        toolsMsgs.put(34667, t6);
        toolsMsgs.put(29720, t7);
        toolsMsgs.put(40187, t8);
        toolsMsgs.put(27336, t9);
        toolsMsgs.put(23395, t10);
        toolsMsgs.put(37568, t11);
        toolsMsgs.put(38960, t12);
        toolsMsgs.put(36552, t13);
        toolsMsgs.put(67, t14);
        toolsMsgs.put(11408, t15);
        toolsMsgs.put(26977, t16);
        toolsMsgs.put(10817, t17);
        toolsMsgs.put(35283, t18);
        toolsMsgs.put(35168, t19);
        toolsMsgs.put(27506, t20);
        toolsMsgs.put(37369, t21);
        return toolsMsgs;
    }
}
